package com.example.demo.exception;


import com.example.demo.entity.CodeMsg;
import com.example.demo.model.exceptionModel;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

@ControllerAdvice
@ResponseBody
public class gloalExceptionHandler {

    @ExceptionHandler(value = Exception.class)//拦截所有异常
    public exceptionModel<String> exceptionHandler(HttpServletRequest request, Exception e){
        e.printStackTrace();
        if(e instanceof  gloalException){
            gloalException ex=(gloalException) e;
            return exceptionModel.error(ex.getCodeMsg());
        }else if(e instanceof BindException){
            BindException ex=(BindException) e;
            List<ObjectError> errors=ex.getAllErrors();//绑定错误返回很多错误，是一个错误列表，只需要第一个错误
            ObjectError error=errors.get(0);
            String msg=error.getDefaultMessage();
            return exceptionModel.error(CodeMsg.BIND_ERROR.fillArgs(msg));
        }else{
            return exceptionModel.error(CodeMsg.SERVER_ERROR);
        }
    }

}
